package ua.com.alus.resvac.crm.services.spring;

import org.apache.lucene.queryParser.ParseException;
import ua.com.alus.resvac.crm.util.search.Search;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.io.IOException;
import java.util.List;

/**
 * Search service implementation
 *
 * @author Usatov Alexey
 */
public class SearchServiceImpl implements SearchService {
    private LuceneService luceneService;

    public void setLuceneService(LuceneService luceneService) {
        this.luceneService = luceneService;
    }

    public static final String SELECT_RESUMES_BY_POS_AND_REGION
            = "SELECT R.PK_UUID, R.POSITION, "
            + "(SELECT C.NAME from CITY C WHERE C.ID=R.FK_CITY_ID), ACC.FIRST_NAME, ACC.LAST_NAME "
            + "FROM RESUME R "
            + "JOIN RESUME_ACCOUNT_DETAILS ACC on (R.FK_ACCOUNT_UUID=ACC.FK_ACCOUNT_UUID) "
            + "WHERE R.PK_UUID IN (";

    public static final String SELECT_VACANCIES_BY_POS_AND_REGION
            = "SELECT V.PK_UUID, V.POSITION, "
            + "(SELECT C.NAME from CITY C WHERE C.ID=V.FK_CITY_ID), ACC.FIRST_NAME, ACC.LAST_NAME "
            + "FROM VACANCY V "
            + "JOIN RESUME_ACCOUNT_DETAILS ACC on (V.FK_ACCOUNT_UUID=ACC.FK_ACCOUNT_UUID) "
            + "WHERE V.PK_UUID IN (";

    @PersistenceContext(unitName = "crmUnit")
    private EntityManager entityManager;

    @SuppressWarnings("unchecked")
    public List<Object> search(Search search) {
        List<String> result = null;
        try {
            result = luceneService.search(search);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (result != null && result.size() > 0) {
            String uids = uidToString(result);
            switch (search.getSearchType()) {
                case RESUME:
                    return (List<Object>) entityManager.createNativeQuery(SELECT_RESUMES_BY_POS_AND_REGION
                            + uids + ")").getResultList();
                case VACANCY:
                    return (List<Object>) entityManager.createNativeQuery(SELECT_VACANCIES_BY_POS_AND_REGION +
                            uids + ")").getResultList();
                default:
                    return null;
            }
        }
        return null;

    }

    private String uidToString(List<String> uidList) {
        StringBuilder result = new StringBuilder();
        for (String uid : uidList) {
            result.append("'").append(uid).append("'").append(",");
        }
        if (result.length() > 0) {
            return result.toString().substring(0, result.length() - 1);
        }
        return result.toString();

    }
}
